import type { ComputedRef, Slots } from "vue"
import type { BasicTableProps, InnerHandlers } from "../types/table"
import { unref, computed, h } from "vue"
import TableHeader from "../components/TableHeader.vue"
import { isString } from "/@/utils/is"
import { getSlot } from "/@/utils/helper/tsxHelper"

export function useTableHeader(propsRef: ComputedRef<BasicTableProps>, slots: Slots, handlers: InnerHandlers) {
  const getHeaderProps = computed((): Recordable => {
    const { title, showTableSetting, titleHelpMessage, isCardTable, tableSetting, rowSelectionTipType, alwaysShowTitle } = unref(propsRef)
    const newShowTableSetting = isCardTable ? false : showTableSetting
    const newAlwaysShowTitle = isCardTable ? true : alwaysShowTitle
    const hideTitle = !slots.tableTitle && !title && !slots.toolbar && !newShowTableSetting
    if (hideTitle && !isString(title)) {
      return {}
    }

    return {
      title: hideTitle
        ? null
        : () =>
            h(
              TableHeader,
              {
                title,
                titleHelpMessage,
                showTableSetting: newShowTableSetting,
                isCardTable,
                tableSetting,
                rowSelectionTipType,
                alwaysShowTitle: newAlwaysShowTitle,
                onColumnsChange: handlers.onColumnsChange,
              } as Recordable,
              {
                ...(slots.toolbar
                  ? {
                      toolbar: () => getSlot(slots, "toolbar"),
                    }
                  : {}),
                ...(slots.tableTitle
                  ? {
                      tableTitle: () => getSlot(slots, "tableTitle"),
                    }
                  : {}),
                ...(slots.headerTop
                  ? {
                      headerTop: () => getSlot(slots, "headerTop"),
                    }
                  : {}),
                ...(slots.tableTop
                  ? {
                      tableTop: () => getSlot(slots, "tableTop"),
                    }
                  : {}),
                // 添加alertAfter插槽
                ...(slots.alertAfter ? { alertAfter: () => getSlot(slots, "alertAfter") } : {}),
              }
            ),
    }
  })
  return { getHeaderProps }
}
